<template>
  <div class="customer-service-chat">
    <div class="chat-header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <h3>在线咨询</h3>
      <div class="status-indicator" :class="{ online: isConnected, offline: !isConnected }">
        <span class="status-dot"></span>
        <span>{{ isConnected ? '在线' : '离线' }}</span>
      </div>
    </div>

    <div class="chat-container" ref="chatContainer">
      <!-- 历史消息 -->
      <div v-if="messages.length === 0" class="empty-messages">
        <p>暂无消息，开始对话吧！</p>
      </div>
      
      <div v-else class="messages-list">
        <div 
          v-for="(msg, index) in messages" 
          :key="index"
          class="message-item"
          :class="{ 'message-user': msg.sender_role === 'user', 'message-service': msg.sender_role === 'service' }"
        >
          <div class="message-content">
            <div class="message-text">{{ msg.content }}</div>
            <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input-area">
      <input 
        type="text" 
        v-model="inputMessage" 
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
        class="message-input"
        :disabled="!isConnected"
      />
      <button 
        class="send-btn" 
        @click="sendMessage"
        :disabled="!isConnected || !inputMessage.trim()"
      >
        发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const ws = ref(null)
const isConnected = ref(false)
const messages = ref([])
const inputMessage = ref('')
const userId = ref(null)
const chatContainer = ref(null)

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

// 获取历史消息
const fetchHistoryMessages = async () => {
  if (!userId.value) return
  
  try {
    const response = await fetch(`http://localhost:8000/api/customer-service/messages/${userId.value}`)
    const data = await response.json()
    if (data.success && data.messages && data.messages.length > 0) {
      // 合并历史消息，避免重复
      const existingTimestamps = new Set(messages.value.map(m => `${m.timestamp}_${m.content}_${m.sender_role}`))
      const newMessages = data.messages.filter(msg => {
        const key = `${msg.timestamp}_${msg.content}_${msg.sender_role}`
        return !existingTimestamps.has(key)
      })
      
      if (newMessages.length > 0) {
        messages.value.push(...newMessages)
        // 按时间排序
        messages.value.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
        scrollToBottom()
        console.log('[客服聊天] 已加载历史消息:', newMessages.length, '条')
      }
    }
  } catch (error) {
    console.error('[客服聊天] 加载历史消息失败:', error)
  }
}

// 初始化WebSocket连接
const initWebSocket = async () => {
  try {
    // 获取或创建用户ID
    const response = await fetch('http://localhost:8000/api/customer-service/user-id', {
      credentials: 'include'
    })
    const data = await response.json()
    userId.value = data.user_id
    
    // 设置Cookie（如果服务器设置了）
    if (response.headers.get('set-cookie')) {
      // Cookie会自动由浏览器处理
    }
    
    // 建立WebSocket连接
    const wsUrl = `ws://localhost:8000/ws/${userId.value}`
    console.log('[客服聊天] 连接WebSocket:', wsUrl)
    
    ws.value = new WebSocket(wsUrl)
    
    ws.value.onopen = () => {
      console.log('[客服聊天] WebSocket连接成功')
      isConnected.value = true
      
      // 同时通过API加载历史消息作为备份
      if (userId.value) {
        fetchHistoryMessages()
      }
    }
    
    ws.value.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('[客服聊天] 收到消息:', data)
        
        if (data.type === 'connection') {
          console.log('[客服聊天] 连接成功:', data.message)
        } else if (data.type === 'history') {
          // 加载历史消息（WebSocket推送的）
          if (data.messages && data.messages.length > 0) {
            // 合并消息，避免重复
            const existingTimestamps = new Set(messages.value.map(m => `${m.timestamp}_${m.content}_${m.sender_role}`))
            const newMessages = data.messages.filter(msg => {
              const key = `${msg.timestamp}_${msg.content}_${msg.sender_role}`
              return !existingTimestamps.has(key)
            })
            
            messages.value.push(...newMessages)
            // 按时间排序
            messages.value.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
            scrollToBottom()
            console.log('[客服聊天] WebSocket历史消息已加载:', newMessages.length, '条')
          }
        } else if (data.type === 'message') {
          // 收到新消息（客服回复）
          const newMessage = {
            sender_id: data.sender_id,
            sender_role: data.sender_role,
            content: data.content,
            timestamp: data.timestamp
          }
          
          // 检查是否已存在（避免重复）
          const exists = messages.value.some(msg => 
            msg.timestamp === newMessage.timestamp && 
            msg.content === newMessage.content &&
            msg.sender_role === newMessage.sender_role
          )
          
          if (!exists) {
            messages.value.push(newMessage)
            scrollToBottom()
            console.log('[客服聊天] 收到客服回复:', newMessage)
          }
        } else if (data.type === 'message_sent') {
          // 消息发送确认 - 也可以在这里添加本地消息显示（如果后端没有立即返回）
          console.log('[客服聊天] 消息已发送')
        } else if (data.type === 'pong') {
          // 心跳响应
          console.log('[客服聊天] 心跳响应')
        }
      } catch (error) {
        console.error('[客服聊天] 解析消息失败:', error)
      }
    }
    
    ws.value.onerror = (error) => {
      console.error('[客服聊天] WebSocket错误:', error)
      isConnected.value = false
    }
    
    ws.value.onclose = () => {
      console.log('[客服聊天] WebSocket连接已关闭')
      isConnected.value = false
      
      // 尝试重连
      setTimeout(() => {
        if (!isConnected.value) {
          console.log('[客服聊天] 尝试重新连接...')
          initWebSocket()
        }
      }, 3000)
    }
    
    // 启动心跳
    setInterval(() => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        ws.value.send(JSON.stringify({ type: 'ping' }))
      }
    }, 30000)
    
  } catch (error) {
    console.error('[客服聊天] 初始化失败:', error)
  }
}

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim() || !isConnected.value) {
    return
  }
  
  const timestamp = new Date().toISOString()
  const message = {
    type: 'chat',
    sender_id: userId.value,
    content: inputMessage.value.trim(),
    timestamp: timestamp
  }
  
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(JSON.stringify(message))
    
    // 立即在本地显示消息（优化用户体验）
    const localMessage = {
      sender_id: userId.value,
      sender_role: 'user',
      content: message.content,
      timestamp: timestamp
    }
    messages.value.push(localMessage)
    scrollToBottom()
    
    inputMessage.value = ''
  }
}

// 返回
const goBack = () => {
  router.push('/home')
}

// 组件挂载时初始化
onMounted(() => {
  initWebSocket()
})

// 组件卸载时关闭连接
onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})
</script>

<style scoped>
.customer-service-chat {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  z-index: 1000;
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.back-btn {
  background: none;
  border: none;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  padding: 4px 8px;
}

.chat-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  flex: 1;
  text-align: center;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
}

.status-indicator.online .status-dot {
  background: #4caf50;
}

.status-indicator.offline .status-dot {
  background: #ccc;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f5f5f5;
}

.empty-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  display: flex;
  margin-bottom: 12px;
}

.message-item.message-user {
  justify-content: flex-end;
}

.message-item.message-service {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 10px 14px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.message-user .message-content {
  background: #ff2442;
  color: white;
}

.message-service .message-content {
  background: white;
  color: #333;
}

.message-text {
  word-wrap: break-word;
  margin-bottom: 4px;
}

.message-time {
  font-size: 10px;
  color: rgba(0,0,0,0.5);
  text-align: right;
}

.message-user .message-time {
  color: rgba(255,255,255,0.7);
}

.chat-input-area {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background: white;
  border-top: 1px solid #e0e0e0;
}

.message-input {
  flex: 1;
  padding: 10px 14px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.message-input:disabled {
  background: #f5f5f5;
  color: #999;
}

.send-btn {
  padding: 10px 24px;
  background: #ff2442;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  font-weight: 500;
}

.send-btn:hover:not(:disabled) {
  background: #e01d37;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>

